package city.spring.modules.material.service.impl;

import city.spring.modules.material.dto.ShelfDTO;
import city.spring.modules.material.entity.ShelfEntity;
import city.spring.modules.material.entity.ShelflevelEntity;
import city.spring.modules.material.repository.ShelfRepository;
import city.spring.modules.material.service.ShelfService;
import city.spring.modules.material.service.ShelflevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service：货架
 *
 * @author 谢金婷
 * @date 2020-07-15 09:55:50
 */
@CacheConfig(cacheNames = {ShelfServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class ShelfServiceImpl extends ServiceImpl<ShelfRepository, ShelfEntity> implements ShelfService {
    private final ShelflevelService shelflevelService;

    public ShelfServiceImpl(ShelflevelService shelflevelService) {
        this.shelflevelService = shelflevelService;
    }

    @Override
    public void saveShelf(ShelfDTO entity) {

        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
        // 循环生成货架格子编号
        for (int i = 1; i <= entity.getHorizontal(); i++) {
            for (int j = 1; j <= entity.getVertical(); j++) {
                System.out.println("i:" + i + "j:" + j);
                ShelflevelEntity shelflevelEntity = new ShelflevelEntity();
                shelflevelEntity.setShelfId(entity.getId());
                shelflevelEntity.setCode(String.valueOf(i) + String.valueOf(j));
                shelflevelEntity.setSname(entity.getCode() + "-" + String.valueOf(i) + "-" + String.valueOf(j));
                shelflevelEntity.setHorizontal(i);
                shelflevelEntity.setVertical(j);
                shelflevelService.saveShelflevel(shelflevelEntity);
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.LOCATION, String.valueOf(shelflevelEntity.getId()));
            }
        }
    }

    @Override
    public void updateShelf(ShelfEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteShelf(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteShelf(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }
}